/**
 * Created by kjmk on 2015/7/13.
 */
//   get/post   sync?  enctype?  callback
var rc_ajax = (function (window) {
    var ajax = {
        createXmlHttpRequest: function () {
            var xmlHttpRequest;
            if (window.ActiveXObject) {
                try {
                    xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                }catch(e){
                    xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
                }
            } else {
                xmlHttpRequest = new XMLHttpRequest();
            }
            return xmlHttpRequest;
        },
        /*值	描述
         application/x-www-form-urlencoded	在发送前编码所有字符（默认）
         multipart/form-data     不对字符编码。在使用包含文件上传控件的表单时，必须使用该值。
         text/plain	空格转换为 "+" 加号，但不对特殊字符编码。*/

        //open(method, url, async, username, password)
        request: function(url, data, callback, method, enctype, async, xmlHttpRequest, nativeCallBack) {
            var fn = function(err){ console.warn("您输入的回调函数有误！"); }
            if(nativeCallBack){
                fn = function () {
                    //console.log(xmlHttpRequest.readyState);
                    if(xmlHttpRequest.readyState === 4){
                        callback(xmlHttpRequest.responseText);
                    }
                }
            }
            xmlHttpRequest.onreadystatechange = fn;
            xmlHttpRequest.open(method, url, async);
            xmlHttpRequest.setRequestHeader("Content-type", enctype);
            try{
                //xmlHttpRequest.setRequestHeader('Accept', 'application/:3000+json; version=1');
                var stmp = this._formatData(data);
                xmlHttpRequest.send(stmp);
            }catch(e) {
            }
        },

        get: function (url, data, callback) {
            this.request( url, data, callback, "GET", "application/x-www-form-urlencoded; charset=UTF-8", true, this.createXmlHttpRequest(), true);
        },

        post: function (url, data, callback) {
            this.request( url, data, callback, "POST", "application/x-www-form-urlencoded; charset=UTF-8", true, this.createXmlHttpRequest(), true);
        },
        
        _formatData : function (obj) {
            if(typeof obj === "object") {
                var s = "";
                for (var k in obj) {
                    s += k + "=" + obj[k];
                }
                return s;
            }else {
                return obj;
            }
        }

    }
    return ajax;
})(window);
